package com.red.wood.module.task;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.DateUtil;
import com.red.wood.common.util.JdbcUtil;
import com.red.wood.common.util.SqlParser;
import com.red.wood.common.util.SysProps;
import com.red.wood.module.model.SqlInfo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class StatisticsTaskHn {
	
	private static final Log log = LogFactory.getLog(StatisticsTaskHn.class);
	
	public static void main(String[] args) {
		Connection dwdConn = null;
		Connection isdmsConn = null;
		Connection mysqlConn = null;
		SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
		try {
			String day = "";
			if(args.length > 0) {
				day = args[0];
				if(!isValidDate(day)) {
					System.exit(0);
				}
			}else {
				day = yyyyMMdd.format(DateUtil.getYesterday());
			}
			log.info("=========数据汇总开始==========");
			log.info("入库时间："+day);
			
			SqlInfo sql = getSqlInfo();
			
			dwdConn = JdbcUtil.getConnection("dwd");
			int cdn_count = getCount(dwdConn,sql.getSqlCdnCount());
			int ircs_count = getCount(dwdConn,sql.getSqlIrcsCount());
			int idc_count = getCount(dwdConn,sql.getSqlIdcCount());
			int dns_count = getCount(dwdConn,sql.getSqlDnsCount());
			int cdn_res_count = getCount(dwdConn,sql.getSqlCdnResCount());
			int ircs_res_count = getCount(dwdConn,sql.getSqlIrcsResCount());
			int idc_res_count = getCount(dwdConn,sql.getSqlIdcResCount());
			int dns_res_count = getCount(dwdConn,sql.getSqlDnsResCount());
			
			isdmsConn = JdbcUtil.getConnection("isdms");
			int icp_count = getCount(isdmsConn,sql.getSqlIcpCount());
			int icp_res_count = getCount(isdmsConn,sql.getSqlIcpResCount());
			
			log.info("CDN企业数："+cdn_count+"，基础数据表总量："+cdn_res_count);
			log.info("IRCS企业数："+ircs_count+"，基础数据表总量："+ircs_res_count);
			log.info("IDC企业数："+idc_count+"，基础数据表总量："+idc_res_count);
			log.info("DNS企业数："+dns_count+"，基础数据表总量："+dns_res_count);
			log.info("备案企业数："+icp_count+"，基础数据表总量："+icp_res_count);
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String query_day = sdf.format(yyyyMMdd.parse(day));
			//云平台、爬虫数据
			mysqlConn = JdbcUtil.getConnection("mysql");
			String sqlIpIpNetMysql = SqlParser.getSql(sql.getSqlIpIpNetMysqlCount(), "query_day", query_day);
			int ipipnet_count = getCount(mysqlConn,sqlIpIpNetMysql);
			
			String sqlCrawlerMysql = SqlParser.getSql(sql.getSqlCrawlerMysqlCount(), "query_day", query_day);
			int crawler_count = getCount(mysqlConn,sqlCrawlerMysql);
			
			log.info("云平台数："+ipipnet_count);
			log.info("爬虫数据："+crawler_count);
			
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			list.add(getMap("CDN","cdn",cdn_count,cdn_res_count,day));
			list.add(getMap("IRCS","ircs",ircs_count,ircs_res_count,day));
			list.add(getMap("IDC","idc",idc_count,idc_res_count,day));
			list.add(getMap("DNS","dns",dns_count,dns_res_count,day));
			list.add(getMap("ICP","icp",icp_count,icp_res_count,day));
			list.add(getMap("IPIPNET","云平台",0,ipipnet_count,day));
			list.add(getMap("CRAWLER","爬虫数据",0,crawler_count,day));
			
			String delSql ="delete from t_st_res_statistics where day="+day;
			JdbcUtil.execSql(isdmsConn, delSql);
			
			String insertSql = "insert into t_st_res_statistics(source_type,source_name,enterprises_count,res_count,day) values (?,?,?,?,?)";
			String columns = "source_type,source_name,enterprises_count,res_count,day";
			JdbcUtil.insertBatchTableData(isdmsConn, list, insertSql, columns, 1000);
			
			log.info("=========数据汇总完成==========");
		}catch(Exception e) {
			log.info("=========数据汇总异常==========");
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}finally {
			JdbcUtil.close(dwdConn);
			JdbcUtil.close(isdmsConn);
			JdbcUtil.close(mysqlConn);
		}
	}
	
	public static Map<String,Object> getMap(String source_type,String source_name,int enterprises_count,int res_count,String day){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("source_type",source_type);
		map.put("source_name",source_name);
		map.put("enterprises_count",enterprises_count);
		map.put("res_count",res_count);
		map.put("day",day);
		return map;
	}
	
	public static int getCount(Connection conn,String sql) {
		int count = 0;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			
			List<Map<String,Object>> list = JdbcUtil.resultSetToList(rs);
			if(list != null && list.size() > 0) {
				String countStr = CommonUtils.valueOf(list.get(0).get("COUNT"));
				if(StringUtils.isNotBlank(countStr)) {
					count = Integer.parseInt(countStr);
				}
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}finally {
			JdbcUtil.close(rs);
			JdbcUtil.close(ps);
		}
		return count;
	}
	
	public static int getHiveCount(Connection conn,String sql) {
		int count = 0;
		PreparedStatement ppst = null;
		ResultSet rs = null;
		try {
			ppst = conn.prepareStatement(sql);
			rs = ppst.executeQuery();
			if(rs.next()) {
				count = rs.getInt("count");
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}finally {
			JdbcUtil.close(rs);
			JdbcUtil.close(ppst);
		}
		return count;
	}
	
	/**
	 * 获取配置文件中的信息
	 * @return
	 */
	public static SqlInfo getSqlInfo() {
		SqlInfo sql = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			xstream.processAnnotations(SqlInfo.class);
			ClassLoader classLoader = StatisticsTaskHn.class.getClassLoader();  
			String xml = IOUtils.toString(classLoader.getResourceAsStream("sqlconfig/sqlInfo.xml"),"UTF-8"); 
			sql = (SqlInfo) xstream.fromXML(xml);
		}catch(Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return sql;
	}
	
	public static boolean isValidDate(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try{
			sdf.setLenient(false);//严格按照给定的格式来校验
			sdf.parse(StringUtils.trim(date));
			return true;
		}catch(Exception e){
			log.error("=========传入的日期错误,正确格式为【yyyyMMdd】且是有效日期=========");
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
			return false;
		}
	}
}